﻿using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Masters.ModuleData;
using Plumber.Sales.ModuleData;
using ApplicationLibrary;

namespace Plumber.Sales.Forms
{
    public partial class Templates : ApplicationLibrary.DBManager.DocumentForm
    {
        private RRSentences RRSentence = null;
        private ListBoxManager<string> SentenceManager = null;
        private PreferencesManager<NHUnspellPref> myLanguage = null;
        private NHUnspellPref NHUnspellPref = null;
        private BindableOject<string> Combine = new BindableOject<string>();
        TemplateType TempType = TemplateType.E_Sale;

        public Templates(TemplateType temptype)
            : base(Properties.Resources.FN_Templates)
        {
            TempType = temptype;

            InitializeComponent();

            myLanguage = new PreferencesManager<NHUnspellPref>(formName, null);
            NHUnspellPref = myLanguage.ReadPreference();
            if (NHUnspellPref.Enable)
                rtbBody.Language = NHUnspellPref.Language;
            else
                rtbBody.SpellingEnable = false;
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarTemplatesParam(txtCode.Text);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerTemplates("templatesForm", new RadarTemplates(TempType), this, TempType);
            dbManager.AddMaster(this, PL_Templates.Name, true);

            FillMasterSource();

            SentenceManager = new ListBoxManager<string>();
            RRSentence = new RRSentences(false);
            RRSentence.Find();
            for (int t = 0; t < RRSentence.Count; t++)
                SentenceManager.AddValue(RRSentence.GetValue<string>(PL_Sentences.Text, t), RRSentence.GetValue<string>(PL_Sentences.Title, t));
            if (RRSentence.Count > 0)
                SentenceManager.AttachTo(lsbSentence);
        }

        protected override void OnPrepareAuxData()
        {
            mlsInvoice.AllLeft();
            if (!string.IsNullOrEmpty(Combine.Value))
            {
                string[] binding = Combine.Value.Split('\t');
                for (int t = 0; t < binding.Length; t++)
                    mlsInvoice.MoveRight(binding[t]);
            }
        }

        private void FillMasterSource()
        {
            RRMasterTypeForInvoice rrMasterType = new RRMasterTypeForInvoice();
            if (rrMasterType.Find())
                for (int t = 0; t < rrMasterType.Count; t++)
                    mlsInvoice.AddLeftValue(rrMasterType.GetValue<string>(PL_MasterType.Code, t),
                                            rrMasterType.GetValue<string>(PL_MasterType.Description, t));
        }

        protected override void OnBindData()
        {
            BindControl(txtCode, PL_Templates.Code);
            BindControl(txtDesc, PL_Templates.Description);
            BindControl(rtbBody, PL_Templates.Body, "Rtf");
            BindObject(Combine, PL_Templates.Combine);
            BindControl(lsbSentence);
            BindControl(mlsInvoice);
        }

        protected override bool OnBeforeSave()
        {
            if (txtCode.Text.Equals(string.Empty))
            {
                MyMessageBox(this, Properties.Resources.Msg_TxtTitle,
                Properties.Resources.Error,
                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            Combine.Value = string.Empty;
            for (int t = 0; t < mlsInvoice.RightCount; t++)
                Combine.Value = Combine.Value.SeparConcat(mlsInvoice.GetKeyRighttAt(t), "\t");

            return base.OnBeforeSave();
        }

        protected override void FocusOnNew()
        {
            txtCode.Focus();
        }

        protected override void OnDisableControlsForEdit()
        {
            txtCode.Enabled = false;
        }

        #endregion

        private void lsbSentence_MouseDown(object sender, MouseEventArgs e)
        {
            int idx = lsbSentence.IndexFromPoint(e.X, e.Y);
            if (e.Button != MouseButtons.Left)
                idx = -1; ;

            if (idx >= 0)
                DoDragDrop(new DataObject(DataFormats.Rtf, lsbSentence.Items[idx].ToString()), DragDropEffects.Copy);
        }

        private void lsbSentence_MouseMove(object sender, MouseEventArgs e)
        {
            int idx = lsbSentence.IndexFromPoint(e.X, e.Y);
            if (idx >= 0 && tltSentence.GetToolTip(lsbSentence) != lsbSentence.Items[idx].ToString())
                tltSentence.SetToolTip(lsbSentence, lsbSentence.Items[idx].ToString());
        }

        private int GetCaretIndexFromPoint(TextBox tb, int x, int y)
        {
            Point p = tb.PointToClient(new Point(x, y));
            int i = tb.GetCharIndexFromPosition(p);
            if (i == tb.Text.Length - 1)
            {
                Point c = tb.GetPositionFromCharIndex(i);
                if (p.X > c.X)
                    i++;
            }
            return i;
        }

        private void rtbBody_RicherDragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.Rtf)
                             ? DragDropEffects.Copy
                             : DragDropEffects.None;
        }

        private void rtbBody_RicherDragOver(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.Rtf)
                             ? DragDropEffects.Copy
                             : DragDropEffects.None;
        }
    }

    #region DbManager Templates

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerTemplates : DBManager
    {
        TemplateType tempType;

        public dbmanagerTemplates(string name, RadarForm radar, DocumentForm document, TemplateType temptype)
            : base(name, radar, document)
        {
            tempType = temptype;
        }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == System.Data.StatementType.Insert)
            {
                if (e.Row[PL_Templates.Type.Name] == System.DBNull.Value)
                    e.Row[PL_Templates.Type.Name] = tempType;
            }
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_Templates();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(PL_Templates.Type, "@p1");
            qB.AddCompare(PL_Templates.Code, "@p2");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sP1 = new SqlABParameter("@p1", PL_Templates.Type);
            sP1.Value = tempType.Int();
            PList.Add(sP1);

            SqlABParameter sP2 = new SqlABParameter("@p2", PL_Templates.Code);
            sP2.Value = "";
            PList.Add(sP2);
            return PList;
        }

        protected override SqlABCommand CreateMasterCommand(ref List<SqlABParameter> dParam)
        {
            return base.CreateMasterCommand(ref dParam);
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = tempType.Int();
            collection.Parameter[1].Value = key[0];
        }
    }

    #endregion

     public class TemplatesSale : Templates
     {
         public TemplatesSale()
             : base(TemplateType.E_Sale)
         {}
     }

     public class TemplatesQuotation : Templates
     {
         public TemplatesQuotation()
             : base(TemplateType.E_Quotation)
         { }
     }
}